require(flextable)
require(tidyverse)
require(gt)

# Load all models
load("00_data/01_data_processed/models_dynamic.Rdata")
load("00_data/01_data_processed/01_revision/st_cluster.Rdata")
load("00_data/01_data_processed/01_revision/aggte_model_epa_region_any_dynamic.Rdata")


# Define table function

options(scipen=999)

create_gt_table <- function(data, filename, title = "", caption="") {
  
  cv <- data$crit.val.egt
  
  # Create the data frame with required transformations
  df <- data.frame(
    `Event.time` = data$egt,
    Estimate = data$att.egt,
    `Std.Error` = data$se.egt
  ) %>%
    mutate(
      upper.ci = Estimate + cv * Std.Error,
      lower.ci = Estimate - cv * Std.Error,
      sig = if_else(sign(upper.ci) == sign(lower.ci), "*", ""),
      `99% Conf. Band` = paste0(
        "[",
        round(lower.ci, 4),
        ", ",
        round(upper.ci, 4),
        "]"
      ),
      Estimate = round(Estimate, 4),
      Std.Error = round(Std.Error, 4)
    ) %>%
    mutate(Estimate = paste0(Estimate, sig)) %>%
    select(`Event.time`,
           Estimate,
           `Std.Error`,
           `99% Conf. Band`) %>%
    rename(`Event time` = `Event.time`,
           `Std. Error` = `Std.Error`)
  
  # Create the gt table
  gt_table <- df %>%
    gt() %>%
    cols_label(
      `Event time` = "Event time",
      Estimate = "Estimate",
      `Std. Error` = "Std. Error",
      `99% Conf. Band` = "99% Conf. Band"
    ) %>%
    tab_footnote(
      footnote = "Note: Signif. codes: * = 99% confidence band does not cover 0, Estimation Method: Doubly Robust (Callaway and Sant’Anna, 2021)"    ) %>%
    tab_options(
      table.width = pct(100),
      table.font.size = px(12),
      data_row.padding = px(5)
    ) %>%
    cols_align(
      align = "center",
      columns = everything()
    ) %>%
    tab_style(
      style = cell_text(size = px(10)),
      locations = cells_footnotes()
    ) 
  return(gt_table)
}

# -----------------------------
# Tables used in Appendix:

# Table A.1
create_gt_table(aggte_model_epa_all_dynamic)

# Table A.2
create_gt_table(aggte_model_excluded_sites_dynamic)

# Table A.3
create_gt_table(aggte_model_state_treatment_dynamic)

# Table A.4
create_gt_table(aggte_model_censored_dynamic)

# Table A.5
create_gt_table(aggte_model_epa_region_dynamic_st_cluster)

# Table A.6
create_gt_table(aggte_model_epa_region_any_dynamic)

# Table A.8
create_gt_table(aggte_model_epa_region_dynamic)

# Table A.9
create_gt_table(aggte_model_epa_on_site_dynamic)

# Table A.10
create_gt_table(aggte_model_epa_off_site_dynamic)

# Table A.11
create_gt_table(aggte_model_non_epa_substitution_dynamic)




